<script setup lang="ts">
import { OrgApi } from '@/apis'

const props = withDefaults(defineProps<Props>(), {
  multiple: false,
  placeholder: '请选择',
  keyword: undefined,
})

const emit = defineEmits(['select'])

interface Props {
  placeholder?: string
  keyword?: string
  multiple?: boolean
}

const model = defineModel<string | number | Array<any>>()

const loading = ref(false)
const campusList = ref<any[]>([])

const getOptionList = (query: any) => {
  loading.value = true
  OrgApi.getList(query).then((res) => {
    campusList.value = res.filter(item => item.orgType === 'CAMPUS')
  }).finally(() => {
    loading.value = false
  })
}

const onChange = (item) => {
  model.value = item.id
  emit('select', item)
}
// 解决select下拉框，分组情况下，回显id的问题
const fallbackOption = (value) => {
  const item = campusList.value.find(item => item.id === value)
  if (item) {
    return {
      value,
      label: item.name,
    }
  } else {
    return {
      value,
      label: value,
    }
  }
}
onMounted(() => {
  getOptionList({ name: props.keyword })
})
</script>

<template>
  <a-select
    v-model="model"
    :placeholder="props.placeholder"
    :loading="loading"
    allow-clear
    :multiple="props.multiple"
    :allow-search="{ retainInputValue: true }"
    value-key="id"
    :fallback-option="fallbackOption"
    @change="onChange"
  >
    <a-option v-for="item in campusList" :key="item.id" :value="item" :label="item.name" />
  </a-select>
</template>

<style scoped>

</style>
